package com.victor9ac.tfm.mashup.connector.adapter.spring.restTemplate;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.web.client.RestTemplate;

import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.net.httpserver.HttpServer;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey.api.client.Client;
import com.victor9ac.tfm.mashup.connector.exception.MashupConnectionException;
import com.victor9ac.tfm.mashup.uris.ConnectionBean;
import com.victor9ac.tfm.mashup.uris.MashupURIFactory;

public class MashupConnectorRestTemplateIt {

	
	private static final String ANY_PORT = "8899";
	static final String ANY_HOST = "localhost";
	static final String RS_CONTEXT = "mashup";
	static final String ANY_RESOURCE_CONTEXT = "comments";
	
	MashupConnectorRestTemplate mashupRestTemplate;
	ConnectionBean connectionBean;
	
    static HttpServer httpServer;
    static Client client = Client.create();
	
	@BeforeClass
	public static void initeEmbeddedRestService() throws Exception{
		
//		connectionBean = new ConnectionBean(ANY_HOST, ANY_PORT, "", RS_CONTEXT);
		
		 try
	        {
			 ResourceConfig resourceConfig = new PackagesResourceConfig(
	                    "com.victor9ac.tfm.mashup.connector.adapter.spring.restTemplate");
			 	
			 	httpServer = HttpServerFactory.create(buildFakeEndpointString(),resourceConfig);

	            httpServer.start();
	            client = Client.create();
	            
	            System.out.println("Created Rest Service embedded and started");
	        }
	        catch (Exception e)
	        {
	            e.printStackTrace();
	            throw e;
	        }
	}


	private static String buildFakeEndpointString() {
		return "http://"+ANY_HOST+":"+ANY_PORT+"/";
	}
	

    @AfterClass
    public static void stop()
    {
        httpServer.stop(0);
        System.out.println("Stopped Rest Service embedded");

    }
	
	@Before
	public void setup (){
		
		mashupRestTemplate = new MashupConnectorRestTemplate(ANY_RESOURCE_CONTEXT);
		mashupRestTemplate.restTemplate = new RestTemplate();
		
		mashupRestTemplate.connectionBean = new ConnectionBean("http",ANY_HOST, ANY_PORT, "", RS_CONTEXT);
		mashupRestTemplate.resourceContext = ANY_RESOURCE_CONTEXT;
		
	}
	
	@Test
	public void test() throws MashupConnectionException {
		
		DummyRestPojo dummyRestPojo = mashupRestTemplate.get("hola", DummyRestPojo.class);
		
		assertNotNull("should have a dummyRestPojo mapped",dummyRestPojo);
	}

}
